//
//  LSZPraisePoetryChartsViewController.m
//  JKFuYinProject
//
//  Created by 九酷 on 2018/7/3.
//  Copyright © 2018年 LC. All rights reserved.
//

#import "LSZPraisePoetryChartsViewController.h"
#import "NetworkTool+LCAVPlay.h"

@interface LSZPraisePoetryChartsViewController ()<UITableViewDataSource,UITableViewDelegate>
{
   NSInteger lastClickRow;
}
@property(nonatomic,strong) UITableView * tableViewAudio;
@property(nonatomic,assign) NSInteger numberPage;
@property(nonatomic,strong) NSMutableArray * mutArrayData;
@property(nonatomic,strong) NSMutableArray * mutAllOriginalArrayData;
@property(nonatomic,assign) NSInteger cliclMoveWhereRow;


@end

@implementation LSZPraisePoetryChartsViewController
-(void)viewWillAppear:(BOOL)animated
{
    [LCFloatingWindow sharedInstance].hidden = YES;/////
}

#pragma mark - 赞美诗排行榜查看是否有缓存
-(void)QueryCacheHymnListData :(NSInteger)number
{
    __weak typeof(self) weakSelf = self;
    [LSZCacheHandling initWithfindPlist:newZanmei_paihangbang :^(BOOL isOk, NSDictionary * dic) {
        if (isOk == YES) {
            LSZleagueTableManager * MG  = [[LSZleagueTableManager alloc]initWithleagueTableManager:dic page:@"1"];
            [weakSelf.mutArrayData removeAllObjects];
            [weakSelf.mutArrayData setArray:MG.mutDataArray];

            [weakSelf.mutAllOriginalArrayData removeAllObjects];
            [weakSelf.mutAllOriginalArrayData setArray:MG.historyArrayData];
            NSString * distinguishValue =  [LSZSpecialPackaging addPlaylistWithArrayData:weakSelf.mutAllOriginalArrayData];
            if ([distinguishValue isEqualToString:@"22_1"]) {
                LCPlaylist *playlistTest = _PlaylistMgr.allPlaylists.firstObject;
                _LCPlayer.songs = playlistTest.allSongs;
            }
            [weakSelf.tableViewAudio reloadData];
            [[NSOperationQueue mainQueue] addOperationWithBlock:^{
                [self.tableViewAudio reloadData];
            }];
        }else{
            [self leagueTable:number];
        }
    }];
}
#pragma mark - 赞美诗的排行榜 1
-(void)leagueTable :(NSInteger)number
{
    __weak typeof(self) weakSelf = self;
    [LSZRequestResolutionDic rankingData:[NSString stringWithFormat:@"%ld",(long)number] :^(BOOL isOk, NSString * str, LSZleagueTableManager *TableManager) {
        if (isOk == YES) {
            if (number == 1) {
                [weakSelf.mutArrayData removeAllObjects];
                [weakSelf.mutArrayData setArray:TableManager.mutDataArray];

                [weakSelf.mutAllOriginalArrayData removeAllObjects];
                [weakSelf.mutAllOriginalArrayData setArray:TableManager.historyArrayData];
            }else{
                [weakSelf.mutArrayData addObjectsFromArray:TableManager.mutDataArray];
                [weakSelf.mutAllOriginalArrayData addObjectsFromArray:TableManager.historyArrayData];
            }
            NSString * distinguishValue =  [LSZSpecialPackaging addPlaylistWithArrayData:weakSelf.mutAllOriginalArrayData];
            if ([distinguishValue isEqualToString:@"22_1"]) {
                LCPlaylist *playlistTest = _PlaylistMgr.allPlaylists.firstObject;
                _LCPlayer.songs = playlistTest.allSongs;
            }
            if(TableManager.mutDataArray.count == 0){
                [weakSelf.tableViewAudio.mj_footer endRefreshingWithNoMoreData];
            }
            [weakSelf.tableViewAudio reloadData];
        }else{
            [SVProgressHUD showErrorWithStatus:[NSString stringWithFormat:@"%@",str]];
            [SVProgressHUD dismissWithDelay:1];
        }
    }];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"排行榜";
    self.mutArrayData = [[NSMutableArray alloc]init];
    self.mutAllOriginalArrayData = [[NSMutableArray alloc]init];
    [self setTableviewUI];
    self.numberPage = 1;
    [self QueryCacheHymnListData:self.numberPage];
    lastClickRow = -1;
    [self addNSNotificationCenter];
}
-(void)setTableviewUI
{
    self.tableViewAudio = [[UITableView  alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight) style:UITableViewStylePlain];
    self.tableViewAudio.dataSource = self;
    self.tableViewAudio.delegate = self;
    //添加以下代码关闭估算行高
    self.tableViewAudio.estimatedRowHeight = 0;
    self.tableViewAudio.estimatedSectionHeaderHeight = 0;
    self.tableViewAudio.estimatedSectionFooterHeight = 0;
    [self.view addSubview:self.tableViewAudio];
    [self.tableViewAudio registerClass:[LSZRandombroadcastHeaderCell class] forHeaderFooterViewReuseIdentifier:@"LSZRandombroadcastHeaderCell"];
    [self.tableViewAudio registerClass:[LSZNewWithPlusSignAudioTableViewCell class] forCellReuseIdentifier:@"LSZNewWithPlusSignAudioTableViewCell"];
    //表的上下拉
    self.tableViewAudio.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        // 进入刷新状态后会自动调用这个block
        self.numberPage = 1;
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            // 刷新表格  和结束刷新
            [self QueryCacheHymnListData:self.numberPage];
            [self.tableViewAudio.mj_header endRefreshing];
        });
    }];
    // 上拉刷新
    self.tableViewAudio.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        // 进入刷新状态后会自动调用这个block
        self.numberPage++;
        //赞美诗的排行榜
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            // 刷新表格  和结束刷新
            [self leagueTable:self.numberPage];
            [self.tableViewAudio.mj_footer endRefreshing];
        });
    }];
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (ScreenWidth == 320) {
        return 45;
    }else if(ScreenWidth == 375){
        return 50;
    }
    else {
        return 58;
    }
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (ScreenWidth == 320) {
        return 35;
    }else if(ScreenWidth == 375){
        return 40;
    }
    else{
        return 48;
    }
}
#pragma mark - 音频有几行
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.mutArrayData.count;
}
- (nullable UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    LSZRandombroadcastHeaderCell * cell = [tableView dequeueReusableHeaderFooterViewWithIdentifier:@"LSZRandombroadcastHeaderCell"];
    [cell.imageViewPlay tapGesture:^(UIGestureRecognizer *ges) {
        [self clickMusicListPlay];
    }];
    [cell.label tapGesture:^(UIGestureRecognizer *ges) {
        [self clickMusicListPlay];
    }];
    [cell.butPaly addTarget:self action:@selector(clickMusicListPlay) forControlEvents:UIControlEventTouchUpInside];
    //当前播放列表clickNowPlayLists
    __weak typeof(self) weakSelf = self;
//    [cell.imageViewList tapGesture:^(UIGestureRecognizer *ges) {
//        [weakSelf clickNowPlayMusicLists];
//    }];
//    cell.nowListsBlock = ^{
//        [weakSelf clickNowPlayMusicLists];
//    };
//    [cell.butList addTarget:self action:@selector(clickNowPlayMusicLists) forControlEvents:UIControlEventTouchUpInside];
    return cell;
}
-(void)clickMusicListPlay
{
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
    [self PlayMusicSongList:indexPath];
}
//-(void)clickNowPlayMusicLists
//{
//    [self example7];
//}
#pragma mark - 点击随机播放
-(void)clickButRandom:(UIButton *)but
{
    LCPlaylist *playlistTest = _PlaylistMgr.allPlaylists.firstObject;
    _LCPlayer.songs = playlistTest.allSongs;
    _LCPlayer.listStatus = LCMusicListStatusAllCycle;//现在是循环播放
    [_LCPlayer playAtIndex:0 isSelectPlay:YES];
}
#pragma mark - 音频的cell
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    LSZNewWithPlusSignAudioTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:@"LSZNewWithPlusSignAudioTableViewCell" forIndexPath:indexPath];
    LSZleagueTableMg * tableMg = nil;
    if (self.mutArrayData.count > indexPath.row) {
        tableMg = self.mutArrayData[indexPath.row];
        cell.labelNumber.text = [NSString stringWithFormat:@"%ld",indexPath.row+1];
        cell.labelSong.text = [NSString stringWithFormat:@"%@",tableMg.title];
        cell.labelAlbums.text = [NSString stringWithFormat:@"%@",tableMg.singerName];
        //耳机
        [LSZSpecialPackaging adaptiveWidth:cell.labelAlbums str:cell.labelAlbums.text sizeMaxWidth:ScreenWidth sizeMaxHeight:cell.labelAlbums.frame.size.height];
        CGRect rect = cell.imageViewHeadset.frame;
        rect.origin.x = CGRectGetMaxX(cell.labelAlbums.frame)+10;
        cell.imageViewHeadset.frame = rect;
        //次数
        CGRect rectPlays = cell.labelPlaysNumber.frame;
        rectPlays.origin.x = CGRectGetMaxX(cell.imageViewHeadset.frame)+2;
        rectPlays.size.width = ScreenWidth-CGRectGetMaxX(cell.imageViewHeadset.frame)-10;
        cell.labelPlaysNumber.frame = rectPlays;
        cell.labelPlaysNumber.text = [NSString stringWithFormat:@"%@次",tableMg.clickConversion];
//        cell.imageViewHeadset.hidden = YES;
//        cell.labelPlaysNumber.hidden = YES;
    }
    cell.butAdd.tag = indexPath.row +1;
    [cell.butAdd addTarget:self action:@selector(clickAddMusicList:) forControlEvents:UIControlEventTouchUpInside];
    cell.butMove.tag = indexPath.row +1;
    [cell.butMove addTarget:self action:@selector(clickMoveMusicList:) forControlEvents:UIControlEventTouchUpInside];
    if (_LCPlayer.selectedIndex == indexPath.row && [[LCHistoryDataManager loadOneSongsData] isEqualToString:cell.labelSong.text] && [cell.labelAlbums.text isEqualToString:_LCPlayer.playingSong.singerName]) {
        [cell didSelectRowCellWithIsSystemRed:YES];
    }else{
        [cell didSelectRowCellWithIsSystemRed:NO];
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}
#pragma mark - 单元格的点击事件
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [self PlayMusicSongList:indexPath];

}
-(void)PlayMusicSongList :(NSIndexPath *)indexPath
{
    LCPlaylist *playlistTest = _PlaylistMgr.allPlaylists.firstObject;
    _LCPlayer.songs = playlistTest.allSongs;
    _LCPlayer.valueDistinguish = @"22_1";
    [_LCPlayer playAtIndex:indexPath.row isSelectPlay:YES];//播放歌曲
    NSInteger lastRow = lastClickRow;
    lastClickRow = (NSInteger)indexPath.row;

    LSZleagueTableMg * tableMg = nil;
    if (self.mutArrayData.count > indexPath.row) {
        tableMg = self.mutArrayData[indexPath.row];
        [LSZRequestData songClickOnTheDataUpdates:tableMg.id_id :^(BOOL isOk, NSString * str, NSDictionary * dic) {
            if (isOk == YES) {
                //点击数更新OK
                tableMg.click = [NSString stringWithFormat:@"%d",[tableMg.click intValue]+1];
                tableMg.clickConversion  = [LSZSpecialPackaging theNumberViewsForTheAlbumAhanges:tableMg.click];
            }
            if (lastRow > 0||lastRow == 0) {
                NSIndexPath *indexPath=[NSIndexPath indexPathForRow:lastRow inSection:0];
                [self.tableViewAudio reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath,nil] withRowAnimation:UITableViewRowAnimationNone];
            }
            [self.tableViewAudio reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath,nil] withRowAnimation:UITableViewRowAnimationNone];
        }];
    }
}
-(void)clickAddMusicList:(UIButton *)but
{
    if ([_LCPlayer.playingSong.singerName isEqualToString:@"圣经新约"] || [_LCPlayer.playingSong.singerName isEqualToString:@"圣经旧约"]) {
        return;
    }
    //已下载
    LCPlaylist *playlist = [LCPlaylist new];
    playlist.name = @"playlist01";
    if (_LCPlayer.songs) {
        playlist.songs = _LCPlayer.songs.mutableCopy;
    }
    JKSongsMessStatus *songsMessStatus;
    NSDictionary *json = [self.mutArrayData[(but.tag - 1)] yy_modelToJSONObject];
    songsMessStatus = [JKSongsMessStatus yy_modelWithJSON:json];
    [self setStringWarning:[NSString stringWithFormat:@"添加歌曲<<%@>>成功!",songsMessStatus.title]];
    [playlist addSongSelectedIndexLater:songsMessStatus];

    _LCPlayer.songs = playlist.allSongs;
    if (_LCPlayer.songs != nil) {
        [[NSNotificationCenter defaultCenter] postNotificationName:@"LCMusicPlayerAddSongNotification" object:self userInfo:nil];
    }
}
-(void)clickMoveMusicList:(UIButton *)butMove
{
    self.cliclMoveWhereRow = butMove.tag - 1;
    LSZleagueTableMg * mg = nil;
    mg = self.mutArrayData[self.cliclMoveWhereRow];
    LSZPopoverViewController * vc = [[LSZPopoverViewController alloc]init];
    [vc show];
    [vc selectIndexRowWith:2];//布局
    [vc getMusicId:mg.id_id];
    [vc distinguishType:@"3"];
    [vc fromWhichInterface:@"LSZPraisePoetryChartsViewController"];
}
-(void)addNSNotificationCenter
{
    NSString * stringCollection = [NSString stringWithFormat:@"%@Collection",@"LSZPraisePoetryChartsViewController"];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(MusicListCollection:) name:stringCollection object:nil];//收藏歌曲成功的通知
    NSString * strShare = [NSString stringWithFormat:@"%@",@"LSZPraisePoetryChartsViewController"];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(InfoNotificationMusicListShare) name:strShare object:nil];//点击分享歌曲的通知
    NSString * strDownload = [NSString stringWithFormat:@"%@Download",@"LSZPraisePoetryChartsViewController"];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(InfoNotificationMusicListDownload) name:strDownload object:nil];//点击下载的通知
    NSString * stringLogin = [NSString stringWithFormat:@"%@Login",@"LSZPraisePoetryChartsViewController"];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(InfoNotificationMusicListLogin) name:stringLogin object:nil];//点击收藏  用户没登录
    //安装播放歌曲发生变化的通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(MusicListPlayerPlayingSongDidChangedNotification:) name:LCMusicPlayerPlayingSongDidChangedNotification object:_LCPlayer];
}
-(void)MusicListCollection:(NSNotification *)notification
{
    NSDictionary * diction = notification.userInfo;
    if ([diction[@"ok"] isEqualToString:@"YES"]) {
        [self setStringWarning:@"收藏成功!"];
    }else{
        [self setStringWarning:diction[@"str"]];
    }
}
#pragma mark  - 分享
- (void)InfoNotificationMusicListShare {
    LSZleagueTableMg * audioMg = nil;
    audioMg = self.mutArrayData[self.cliclMoveWhereRow];
    [self shareAudioWithImageArray:@[audioMg.image] url:audioMg.fileUrl musicWebURL:audioMg.shareUrl title:audioMg.title contentMessage:audioMg.singerName type:(SSDKContentTypeAudio)];
}
#pragma mark - 下载
-(void)InfoNotificationMusicListDownload
{
    JKSongsMessStatus *songsMessStatus;
    LSZleagueTableMg * mg = nil;
    mg = self.mutArrayData[self.cliclMoveWhereRow];
    NSDictionary *json = [mg yy_modelToJSONObject];
    songsMessStatus = [JKSongsMessStatus yy_modelWithJSON:json];
    [kNetworkTool downloadSongWithUrl:songsMessStatus];//下载歌曲文件
}
#pragma mark - 收到通知  用户未登录
-(void)InfoNotificationMusicListLogin
{
     if([[_UserM usercode] isEqualToString:@""]){
        pushAccLoginVC;
    }
}
- (void)MusicListPlayerPlayingSongDidChangedNotification:(NSNotification *)notification {
    [self.tableViewAudio reloadData];
}
- (void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
@end
